package com.cashmate.struts;

import com.cashmate.hibernate.dao.LoansDAO;
import com.cashmate.hibernate.dao.RatesDAO;
import com.cashmate.hibernate.dao.VoucherDAO;
import com.cashmate.hibernate.pojo.Checks;
import com.cashmate.hibernate.pojo.Employees;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;

import com.cashmate.hibernate.pojo.Loans;
import com.cashmate.hibernate.pojo.Rates;
import com.cashmate.hibernate.pojo.Voucher;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

public class Release_PrintAcknowledgement extends ActionSupport{
  private LoansDAO loanDAO = (LoansDAO) ServletActionContext.getServletContext().getAttribute("loansDAO");
  private VoucherDAO voucherDAO = (VoucherDAO) ServletActionContext.getServletContext().getAttribute("voucherDAO");
  private RatesDAO rateDAO = (RatesDAO) ServletActionContext.getServletContext().getAttribute("ratesDAO");
  private String selected;
  private String loc;


  @Actions( {
    @Action(value = "/printacknowledgement", results = {
    })
  })
  public String execute()
  {
      
      Employees empl = (Employees) ServletActionContext.getRequest().getSession().getAttribute("employee");
      
      SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
      SimpleDateFormat format2 = new SimpleDateFormat("MMddyyyy");
      NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.ROOT);
      
      HttpServletResponse response = ServletActionContext.getResponse();
      HttpServletRequest request = ServletActionContext.getRequest();
      
        response.setContentType("application/pdf");
        
        selected = request.getParameter("selected");
        String loans[] = selected.split(",");
        try{
        Rectangle rect = new Rectangle(612, 324);
        Document document = new Document();
        document.setPageSize(rect);
        document.setMargins(36, 36, 10, 10);
        
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
        writer.addViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);       

        document.open();
        
        StringBuffer javascript = new StringBuffer();
 
        javascript.append("var params = this.getPrintParams();");

        javascript.append("params.interactive =	params.constants.interactionLevel.silent;");
        javascript.append("params.printerName=\"MY_PRINTER_NAME\";");
        javascript.append("params.pageHandling = params.constants.handling.shrink;");

        PdfAction pdfAction= PdfAction.javaScript(javascript.toString(), writer);
        writer.addJavaScript(pdfAction);
        
        Paragraph emp = new Paragraph("");
        
        for(String l : loans){
            Loans loan = new Loans();
            int loanid = 0;
            try{
                loanid = Integer.parseInt(l);
                loan = loanDAO.get(loanid);
            }catch(Exception e){
                
            }
            
            //replaceables
                String name = loan.getCompletename();
                String addressLine1 = loan.getBorrowers().getStreetaddress() + " " + loan.getBorrowers().getBarangay() +",";
                String addressLine2 = loan.getBorrowers().getCityormunicipality() + ", " + loan.getBorrowers().getProvince() + " " + loan.getBorrowers().getPostalcode();
                String loanAccountNo = loan.getAccount();
                String loanNo = loan.getLoanno() + "";
                
                Voucher voucher = new Voucher();
                for(Voucher v : loan.getVouchers()){
                    voucher = v;
                }
                
                Checks check = new Checks();
                for(Checks c : loan.getCheckses()){
                    check = c;
                }            
                
                String voucherNo = voucher.getDocuments().getDocumentno();
                String checkNo = check.getCheckno();
                String checkDate = check.getCheckdate();
                
                double principal = loan.getLoanamount();
                DetachedCriteria criteria = criteria = DetachedCriteria.forClass(Rates.class);
                criteria.createCriteria("products", "p").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);          
                criteria.add(Restrictions.eq("p.productid", loan.getLoanverification().getProducts().getProductid()));
                int sizeofrate = rateDAO.countByCriteria(criteria);
                criteria.setProjection(null);
                criteria.setResultTransformer(Criteria.ROOT_ENTITY);
                List<Rates> rates = rateDAO.findByCriteria(criteria, 0, sizeofrate);
                double[] minus = new double[rates.size()];
                String[] minusNames = new String[rates.size()];
                
                double deductions = 0;
                
                for(int o = 0; o < minus.length; o++){
                    
                    if(rates.get(o).getRatename().equalsIgnoreCase("Documentation and Notarial Fee") && rates.get(o).getProducts().getProductname() == 100){
                        minus[o] = (principal * rates.get(o).getRate()) + 10 ;
                    }else{
                        minus[o] = principal * rates.get(o).getRate();
                    }
                    
                    minusNames[o] = rates.get(o).getRatename();                    
                    deductions += minus[o];
                }
                
                double netProceeds = principal - deductions;
                String date = format.format(new Date());
                
                String acknowledgementNo = "AR" + voucher.getDocuments().getDocumentno().substring(1);
                
                Font fontInfo = new Font(FontFamily.HELVETICA, 8);
                Font fontInfoHead = new Font(FontFamily.HELVETICA, 8, Font.BOLDITALIC);
                Font fontAddInfo = new Font(FontFamily.HELVETICA, 8, Font.ITALIC);
                Font fontVerif = new Font(FontFamily.HELVETICA, 8, Font.UNDERLINE);
            
            PdfPTable acknowledgement = new PdfPTable(1);
            acknowledgement.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            acknowledgement.setWidthPercentage(100);
            
            Paragraph titleAcknowledgement = new Paragraph("CASHMATE CREDIT CORPORATION", fontInfoHead);
            Paragraph titlePayment = new Paragraph("PAYMENT DETAILS", fontAddInfo);
            
            PdfPCell titleAck = new PdfPCell(titleAcknowledgement);
            titleAck.setBorder(Rectangle.NO_BORDER);
            titleAck.setHorizontalAlignment(Element.ALIGN_CENTER);
            
            PdfPCell titlePay = new PdfPCell(titlePayment);
            titlePay.setBorder(Rectangle.NO_BORDER);
            titlePay.setHorizontalAlignment(Element.ALIGN_CENTER);
            
            float[] forAct = {1f, 3f, 2f, 1f};
            PdfPTable firstInfo = new PdfPTable(forAct);
            firstInfo.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            firstInfo.setWidthPercentage(100);
            
            Paragraph parTo = new Paragraph("To:", fontAddInfo);
            Paragraph parBor = new Paragraph(name, fontInfo);
            Paragraph parHLoANu = new Paragraph("Loan Account Number", fontAddInfo);
            Paragraph parInfLoanAcctNu = new Paragraph(loanAccountNo, fontInfo);
            Paragraph parAddress1 = new Paragraph(addressLine1, fontInfo);
            Paragraph parAddress2 = new Paragraph(addressLine2, fontInfo);
            Paragraph parHLoNu = new Paragraph("Loan Number", fontAddInfo);
            Paragraph parInfLoanNu = new Paragraph(loanNo, fontInfo);
            Paragraph parHVoNu = new Paragraph("Voucher Number", fontAddInfo);
            Paragraph parInfVouNu = new Paragraph(voucherNo, fontInfo);
            Paragraph parHChNu = new Paragraph("Check Number", fontAddInfo);
            Paragraph parInfCheNu = new Paragraph(checkNo, fontInfo);
            Paragraph parHCheDa = new Paragraph("Check Date", fontAddInfo);
            Paragraph parInfCheDa = new Paragraph(checkDate, fontInfo);
            
            PdfPCell infoLoanAcctNu = new PdfPCell(parInfLoanAcctNu);
            infoLoanAcctNu.setBorder(Rectangle.NO_BORDER);
            infoLoanAcctNu.setHorizontalAlignment(Element.ALIGN_RIGHT);
            PdfPCell infoLoanNu = new PdfPCell(parInfLoanNu);
            infoLoanNu.setBorder(Rectangle.NO_BORDER);
            infoLoanNu.setHorizontalAlignment(Element.ALIGN_RIGHT);
            PdfPCell infoVouNu = new PdfPCell(parInfVouNu);
            infoVouNu.setBorder(Rectangle.NO_BORDER);
            infoVouNu.setHorizontalAlignment(Element.ALIGN_RIGHT);
            PdfPCell infoCheNu = new PdfPCell(parInfCheNu);
            infoCheNu.setBorder(Rectangle.NO_BORDER);
            infoCheNu.setHorizontalAlignment(Element.ALIGN_RIGHT);
            PdfPCell infoCheDa = new PdfPCell(parInfCheDa);
            infoCheDa.setBorder(Rectangle.NO_BORDER);
            infoCheDa.setHorizontalAlignment(Element.ALIGN_RIGHT);
            
            PdfPCell infAddressLine2 = new PdfPCell(parAddress2);
            infAddressLine2.setBorder(Rectangle.NO_BORDER);
            infAddressLine2.setRowspan(3);
            
            firstInfo.addCell(parTo);
            firstInfo.addCell(parBor);
            firstInfo.addCell(parHLoANu);
            firstInfo.addCell(infoLoanAcctNu);
            firstInfo.addCell(emp);
            firstInfo.addCell(parAddress1);
            firstInfo.addCell(parHLoNu);
            firstInfo.addCell(infoLoanNu);
            firstInfo.addCell(emp);
            firstInfo.addCell(infAddressLine2);
            firstInfo.addCell(parHVoNu);
            firstInfo.addCell(infoVouNu);
            firstInfo.addCell(emp);
            firstInfo.addCell(parHChNu);
            firstInfo.addCell(infoCheNu);
            firstInfo.addCell(emp);
            firstInfo.addCell(parHCheDa);
            firstInfo.addCell(infoCheDa);
            
            float[] forSec = {2f, 4f, 1f, 1f};
            PdfPTable secondaryInfo = new PdfPTable(forSec);
            secondaryInfo.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            secondaryInfo.setWidthPercentage(100);
            
            Paragraph ackNo = new Paragraph(acknowledgementNo, fontInfoHead);
            
            Paragraph parHPrin = new Paragraph("Principal", fontInfo);
            Paragraph parHInte = new Paragraph(minusNames[0], fontInfo);
            Paragraph parHHand = new Paragraph(minusNames[1], fontInfo);
            Paragraph parHDocu = new Paragraph(minusNames[2], fontInfo);
            Paragraph parHCred = new Paragraph(minusNames[3], fontInfo);
            Paragraph parHProc = new Paragraph("Net Loan Proceeds", fontInfo);
            
            Paragraph parIPrin = new Paragraph(nf.format(principal).substring(2, nf.format(principal).length()) + "", fontInfo);
            Paragraph parIInte = new Paragraph("(" + nf.format(minus[0]).substring(2, nf.format(minus[0]).length()) + ")", fontInfo);
            Paragraph parIHand = new Paragraph("(" + nf.format(minus[1]).substring(2, nf.format(minus[1]).length()) + ")", fontInfo);
            Paragraph parIDocu = new Paragraph("(" + nf.format(minus[2]).substring(2, nf.format(minus[2]).length()) + ")", fontInfo);
            Paragraph parICred = new Paragraph("(" + nf.format(minus[3]).substring(2, nf.format(minus[3]).length()) + ")", fontInfo);
            Paragraph parIProc = new Paragraph(nf.format(netProceeds).substring(2, nf.format(netProceeds).length()), fontInfo);
            
            PdfPCell ackBottom = new PdfPCell(emp);
            ackBottom.setBorder(Rectangle.BOTTOM);
            ackBottom.setColspan(2);
            
            PdfPCell ackNoCell = new PdfPCell(ackNo);
            ackNoCell.setRowspan(6);
            ackNoCell.setBorder(Rectangle.NO_BORDER);
            ackNoCell.setVerticalAlignment(Element.ALIGN_BOTTOM);
            ackNoCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            
            PdfPCell hCred = new PdfPCell(parHCred);
            hCred.setBorder(Rectangle.BOTTOM);
            hCred.setPaddingBottom(5);
            
            PdfPCell hProc = new PdfPCell(parHProc);
            hProc.setBorder(Rectangle.BOTTOM);
            hProc.setPaddingBottom(5);
            
            PdfPCell iPrin = new PdfPCell(parIPrin);
            iPrin.setBorder(Rectangle.NO_BORDER);
            iPrin.setHorizontalAlignment(Element.ALIGN_RIGHT);
            PdfPCell iInte = new PdfPCell(parIInte);
            iInte.setBorder(Rectangle.NO_BORDER);
            iInte.setHorizontalAlignment(Element.ALIGN_RIGHT);
            PdfPCell iHand = new PdfPCell(parIHand);
            iHand.setBorder(Rectangle.NO_BORDER);
            iHand.setHorizontalAlignment(Element.ALIGN_RIGHT);
            PdfPCell iDocu = new PdfPCell(parIDocu);
            iDocu.setBorder(Rectangle.NO_BORDER);
            iDocu.setHorizontalAlignment(Element.ALIGN_RIGHT);
            PdfPCell iCred = new PdfPCell(parICred);
            iCred.setBorder(Rectangle.BOTTOM);
            iCred.setPaddingBottom(5);
            iCred.setHorizontalAlignment(Element.ALIGN_RIGHT);
            PdfPCell iProc = new PdfPCell(parIProc);
            iProc.setBorder(Rectangle.BOTTOM);
            iProc.setHorizontalAlignment(Element.ALIGN_RIGHT);
            
            PdfPCell empBot = new PdfPCell(emp);
            empBot.setBorder(Rectangle.BOTTOM);
            empBot.setColspan(2);
                        
            secondaryInfo.addCell(ackNoCell);
            secondaryInfo.addCell(parHPrin);
            secondaryInfo.addCell(iPrin);
            secondaryInfo.addCell(emp);
            secondaryInfo.addCell(parHInte);
            secondaryInfo.addCell(iInte);            
            secondaryInfo.addCell(emp);
            secondaryInfo.addCell(parHHand);
            secondaryInfo.addCell(iHand);
            secondaryInfo.addCell(emp);          
            secondaryInfo.addCell(parHDocu);
            secondaryInfo.addCell(iDocu);
            secondaryInfo.addCell(emp);
            secondaryInfo.addCell(hCred);
            secondaryInfo.addCell(iCred);
            secondaryInfo.addCell(emp);
            secondaryInfo.addCell(hProc);
            secondaryInfo.addCell(iProc);
            secondaryInfo.addCell(emp); 
            secondaryInfo.addCell(emp);
            secondaryInfo.addCell(empBot);
            secondaryInfo.addCell(emp);
            
            Paragraph titAck = new Paragraph("Acknowledgement Receipt", fontAddInfo);
            
            PdfPCell titleAckn = new PdfPCell(titAck);
            titleAckn.setHorizontalAlignment(Element.ALIGN_CENTER);
            titleAckn.setBorder(Rectangle.NO_BORDER);
            
            PdfPCell filler1 = new PdfPCell(emp);
            filler1.setBorder(Rectangle.NO_BORDER);
            filler1.setFixedHeight(7);
            PdfPCell filler2 = new PdfPCell(emp);
            filler2.setBorder(Rectangle.TOP);
            filler2.setBorderWidth(1);
            filler2.setFixedHeight(7);
                        
            acknowledgement.addCell(titleAck);
            acknowledgement.addCell(titlePay);
            acknowledgement.addCell(firstInfo);
            acknowledgement.addCell(secondaryInfo);
            acknowledgement.addCell(filler1);
            acknowledgement.addCell(filler2);
            acknowledgement.addCell(titleAck);
            acknowledgement.addCell(titleAckn);
            acknowledgement.addCell(firstInfo);
            
            float[] forThird = {1f, 1f, 1f, 1f, 1f, 1f};
            PdfPTable tertiaryInfo = new PdfPTable(forThird);
            tertiaryInfo.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            tertiaryInfo.setWidthPercentage(100);
            
            PdfPCell iAck = new PdfPCell(ackNo);
            iAck.setRowspan(2);
            iAck.setBorder(Rectangle.NO_BORDER);
            iAck.setHorizontalAlignment(Element.ALIGN_CENTER);
            iAck.setVerticalAlignment(Element.ALIGN_BOTTOM);
            
            Paragraph parReceive = new Paragraph("Received By:", fontAddInfo);
            Paragraph parDate = new Paragraph("Date:", fontAddInfo);
            Paragraph parBorrower = new Paragraph(name, fontVerif);
            Paragraph parDateNow = new Paragraph(date, fontInfo);
            
            PdfPCell borrowerCell = new PdfPCell(parBorrower);
            borrowerCell.setBorder(Rectangle.NO_BORDER);
            borrowerCell.setColspan(3);
            
            PdfPCell dateCell = new PdfPCell(parDateNow);
            dateCell.setBorder(Rectangle.BOTTOM);
            dateCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            
            tertiaryInfo.addCell(iAck);
            tertiaryInfo.addCell(parReceive);
            tertiaryInfo.addCell(emp);
            tertiaryInfo.addCell(emp);
            tertiaryInfo.addCell(parDate);
            tertiaryInfo.addCell(emp);
            tertiaryInfo.addCell(borrowerCell);
            tertiaryInfo.addCell(dateCell);
            tertiaryInfo.addCell(emp);  
            
            acknowledgement.addCell(tertiaryInfo);
                      
            document.add(acknowledgement);    
            document.newPage();
            
            loan.setAcknowledgementprint(true);
            loanDAO.update(loan);
        }
        
        document.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    
    return NONE;
  }  

    public void setSelected(String selected) {
        this.selected = selected;
    }    

    public String getLoc() {
        return loc;
    }
  

}
